package com.ccl.iot.controler;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ccl.iot.publics.Messager;
import com.ccl.iot.privates.MultiFunc5525IconBuilder;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.publics.UIUtils;
import com.ccl.iot.updater.HttpHelper;
import com.ccl.iot.updater.HttpHelper.HttpDownloadListener;
import com.ccl.iot.IOTCallback.UpgradeProgressCallback;
import com.ccl.iot.device.IOTDeviceConst;
import com.ccl.iot.device.IOTMultiFunc5525;
import com.ccl.iot.IOTNetAPI;
import com.ccl.iot.IOTNetAPIEnum;
import com.ccl.iot.dialogs.NoTitleDialog;
import com.ccl.iot.R;

public class MiniMultiFunc5525View extends MiniControlerView {

    private Paint iPaint = new Paint();

    private boolean iPressing = false;

    private int mType;
    private int mBrand;
    private int mModel;

    public MiniMultiFunc5525View(Context context, IOTMultiFunc5525 aDevice) {
        super(context, aDevice);
        iPaint.setAntiAlias(true);
        iPaint.setDither(true);
        bindDevice();
    }

    @Override
    public void bindDevice() {
        super.bindDevice();

        if (getItem() != null) {
            // getItem().addStateChangeListener(this);

            super.setOnTouchListener(iOnTouchListener);
            super.setOnClickListener(iOnClickListener);
        }
    }

    @Override
    public void unBindDevice() {
        if (getItem() != null) {
            // getItem().removeStateChangeListener(this);
        }

        super.unBindDevice();

        super.setOnTouchListener(null);
        super.setOnClickListener(null);
    }

    @Override
    public IOTMultiFunc5525 getItem() {
        return (IOTMultiFunc5525) iItem;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Rect tRect = super.getItemRect();

        if (tRect != null) {
            Bitmap tIcon = null;
            tIcon = MultiFunc5525IconBuilder.Build(tRect.width(), tRect.height(), getItem() != null && getItem().isOnline(), ((IOTMultiFunc5525) iItem).hasPatch(), iPressing, getItem() != null ? getItem().getAuth() : IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_NONE, getItem().getSplitIconId());

            if (tIcon != null) {
                canvas.drawBitmap(tIcon, tRect.left, tRect.top, iPaint);
            } else {
                iPaint.setColor(Color.DKGRAY);

                canvas.drawRect(tRect, iPaint);
            }
        }

        super.onDraw(canvas);
    }

    private View.OnClickListener iExOnClickListener = null;

    @Override
    public void setOnClickListener(OnClickListener l) {
        iExOnClickListener = l;
    }

    private View.OnClickListener iOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getVisibility() == VISIBLE) {
                if (isDeviceBind()) {
                    final IOTMultiFunc5525 dev = getItem();
                    if (!checkAuth(dev)) {
                        return;
                    }

                    if (dev.getAuth() != IOTNetAPIEnum.EAUTH_STATE.EAUTH_STATE_OWNER) {
                        Messager.Show(getContext().getString(R.string.Can_Not_Install));
                        return;
                    }


                    // TODO 添加补丁(5525)

                    View view = inflate(getContext(), R.layout.dialog_5525_modify_model, null);

                    final TextView type = (TextView) view.findViewById(R.id.device_type);
                    final TextView brand = (TextView) view.findViewById(R.id.device_brand);
                    final TextView model = (TextView) view.findViewById(R.id.device_model);
                    type.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            final CharSequence[] items = {getContext().getString(R.string.Air), getContext().getString(R.string.Probe)};
                            AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                            builder.setTitle(R.string.Switch_Type);
                            builder.setSingleChoiceItems(items, -1, new android.content.DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(android.content.DialogInterface dialog, int which) {
                                    type.setText(items[which]);

                                    switch (which) {
                                        case 0:
                                            mType = IOTDeviceConst.TDEVICE_TYPE.EDEVICE_TYPE_TERMINAL_AIR_CONDITION_8;
                                            brand.setText("");
                                            break;

                                        case 1:
                                            mType = IOTDeviceConst.TDEVICE_TYPE.EDEVICE_TYPE_TERMINAL_ANTI_THEFT_PROBE;
                                            brand.setText(R.string.No_Brand);
                                            mBrand = 1;
                                            break;
                                    }

                                    model.setText("");
                                    dialog.cancel();
                                }
                            });
                            builder.show();
                        }
                    });
                    brand.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            if (mType == IOTDeviceConst.TDEVICE_TYPE.EDEVICE_TYPE_TERMINAL_ANTI_THEFT_PROBE) {
                                return;
                            } else if (mType == 0) {
                                Messager.Show(R.string.Switch_Type, 0);
                                return;
                            }

                            final CharSequence[] items = {"大金"};
                            AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                            builder.setTitle(R.string.Switch_Brand);
                            builder.setSingleChoiceItems(items, -1, new android.content.DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(android.content.DialogInterface dialog, int which) {
                                    brand.setText(items[which]);
                                    switch (which) {
                                        case 0:
                                            mBrand = 1;
                                            break;
                                    }

                                    model.setText("");
                                    dialog.cancel();
                                }
                            });
                            builder.show();
                        }
                    });
                    model.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {

                            CharSequence[] items = null;
                            int tmp = 0;
                            if (mType == IOTDeviceConst.TDEVICE_TYPE.EDEVICE_TYPE_TERMINAL_ANTI_THEFT_PROBE) {
                                items = new CharSequence[]{"16"};
                                tmp = 16;
                            } else if (mType != 0) {
                                if (mBrand == 0) {
                                    Messager.Show(R.string.Switch_Brand, 0);
                                    return;
                                }

                                items = new CharSequence[]{"8"};
                                tmp = 8;
                            } else {
                                if (mBrand == 0) {
                                    Messager.Show(getContext().getString(R.string.Switch_Brand_Type), 0);
                                } else {
                                    Messager.Show(R.string.Switch_Type, 0);
                                }

                                return;
                            }

                            final CharSequence[] newItems = items;
                            final int newTmp = tmp;

                            AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                            builder.setTitle(R.string.Switch_Model);
                            builder.setSingleChoiceItems(items, -1, new android.content.DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(android.content.DialogInterface dialog, int which) {
                                    model.setText(newItems[which]);
                                    mModel = newTmp;
                                    dialog.cancel();
                                }
                            });
                            builder.show();

                        }
                    });

                    AlertDialog.Builder ad = new Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

                    ad.setNegativeButton(R.string.OK, new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(android.content.DialogInterface dialog, int which) {
                            final int uuid = mModel | (mBrand << 16) | (mType << 24);
                            if (uuid == 0) {
                                Messager.Show(R.string.Switch_Type, 0);
                                return;
                            }

                            String url = null;
                            switch (uuid) {
                                case IOTDeviceConst.PATCH_UUID.EPATCH_UUID_AC_DAIKIN_VRV_8CH:
                                    url = "http://iot.cclcp.com:5499/Downloads/Patch/" + Integer.toHexString(uuid) + "/patch.bin";
                                    break;
                                case IOTDeviceConst.PATCH_UUID.EPATCH_UUID_AT_RF_PROBE_16CH:
                                    url = "http://iot.cclcp.com:5499/Downloads/Patch/" + Integer.toHexString(uuid) + "/patch.bin";
                                    break;

                                default:
                                    break;
                            }

                            if (url != null) {
                                final String filePath = getContext().getFilesDir().getAbsolutePath() + "/patch.bin";

                                final NoTitleDialog d = new NoTitleDialog(getContext());

                                View view = inflate(getContext(), R.layout.dialog_upgrade_rom, null);
                                final TextView des = (TextView) view.findViewById(R.id.dialog_upgrade_tv_des);
                                final TextView progress = (TextView) view.findViewById(R.id.dialog_upgrade_tv_progress);
                                final ProgressBar pb = (ProgressBar) view.findViewById(R.id.dialog_upgrade_pb);

                                des.setText(R.string.Downloading);
                                progress.setText("0%");
                                d.setCanceledOnTouchOutside(false);
                                d.setCancelable(false);
                                d.setContentView(view);
                                d.show();

                                final String newUrl = url;
                                ThreadPoolUtils.getInstance().addTask(new Runnable() {

                                    @Override
                                    public void run() {
                                        int result = HttpHelper.GetHttpRequestFile(newUrl, filePath, new HttpDownloadListener() {

                                            @Override
                                            public void onDownloadProgress(final int aSize, final int aPos) {
                                                pb.setMax(aSize);
                                                pb.setProgress(aPos);
                                                UIUtils.postTaskSafely(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        progress.setText(((long) aPos) * 100 / aSize + "%");
                                                    }
                                                });

                                                if (aPos >= aSize) {
                                                    UIUtils.postTaskSafely(new Runnable() {

                                                        @Override
                                                        public void run() {
                                                            des.setText(R.string.DownLoadSuccess);
                                                        }
                                                    });

                                                    SystemClock.sleep(1000);

                                                    UIUtils.postTaskSafely(new Runnable() {

                                                        @Override
                                                        public void run() {
                                                            des.setText(R.string.Start_Install);
                                                            pb.setProgress(0);
                                                            progress.setText("0%");
                                                        }
                                                    });

                                                    boolean installResult = IOTNetAPI.GetInstance().installPatch(filePath, dev.getID(), uuid, 2, new UpgradeProgressCallback() {

                                                        @Override
                                                        public void onUpgradeProgressCallback(long aDevID, final int aTotal, final int aProgress) {
                                                            pb.setMax(aTotal);
                                                            pb.setProgress(aProgress);

                                                            UIUtils.postTaskSafely(new Runnable() {

                                                                @Override
                                                                public void run() {
                                                                    progress.setText(((long) aProgress) * 100 / aTotal + "%");

                                                                    if (aProgress >= aTotal) {
                                                                        des.setText(R.string.Install_Success);
                                                                        d.cancel();
                                                                        Messager.Show(R.string.Install_Success, 0);

                                                                    }
                                                                }
                                                            });
                                                        }
                                                    });

                                                    if (!installResult) {
                                                        UIUtils.postTaskSafely(new Runnable() {

                                                            @Override
                                                            public void run() {
                                                                d.cancel();
                                                                Messager.Show(getContext().getString(R.string.Install_Faild), 0);
                                                            }
                                                        });
                                                    }
                                                }
                                            }
                                        });
                                        if (result == -1) {
                                            UIUtils.postTaskSafely(new Runnable() {

                                                @Override
                                                public void run() {
                                                    d.cancel();
                                                    Messager.Show(getContext().getString(R.string.Install_Faild), 0);
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        }

                    });
                    ad.setOnCancelListener(new DialogInterface.OnCancelListener() {

                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mModel = 0;
                            mBrand = 0;
                            mType = 0;
                        }
                    });

                    ad.setPositiveButton(R.string.Cancel, null);
                    ad.setView(view);
                    AlertDialog dialog = ad.create();

                    dialog.show();
                }
            }

            if (iExOnClickListener != null) {
                iExOnClickListener.onClick(v);
            }
        }
    };

    private View.OnTouchListener iOnTouchListener = new View.OnTouchListener() {
        float moveY = -1;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            IOTMultiFunc5525 dev = getItem();
            if (dev != null && dev.isOnline()) {
                if (event != null) {
                    int tAction = event.getAction();

                    if (tAction == MotionEvent.ACTION_DOWN) {
                        moveY = -1;
                        iPressing = true;

                        requestDisallowInterceptTouchEvent(true);
                    } else if (tAction == MotionEvent.ACTION_UP) {
                        moveY = -1;
                        if (iPressing) {
                            iPressing = false;
                        }
                    } else if (tAction == MotionEvent.ACTION_CANCEL) {
                        moveY = -1;
                        iPressing = false;
                    } else if (tAction == MotionEvent.ACTION_MOVE) {

                        requestDisallowInterceptTouchEvent(true);
                        if (moveY == -1) {
                            moveY = event.getY();
                        }
                        if (moveY == event.getY()) {
                            requestDisallowInterceptTouchEvent(true);
                        } else {
                            if (Math.abs(moveY - event.getY()) <= 10) {
                                requestDisallowInterceptTouchEvent(true);
                            } else {
                                requestDisallowInterceptTouchEvent(false);
                            }

                        }

                    } else {
                        return false;
                    }

                    postInvalidate();

                    return true;
                }
            }

            return false;
        }
    };

//	@Override
//    public void onStateChanged(IOTInterface.IOTStateMonitorInterface aSource, int aNewState) {
//		this.postInvalidate();
//	}

}
